<template>
  <div>
    <h1>promise</h1>
    <div>
      数字:<input type="number" v-model="num">
    </div>
    <button @click="checkNum()">判断</button>
    <div>
      {{ result }}
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      num: '',
      result: ''
    }
  },
  methods: {
    checkNum () {
      async function check (n) {
        let a = checkParity(n)
        let b = check10(n)
        let arr = [a, b]
        // 竞争取一，或
        // await Promise.race(arr)
        // 同步进行，且 ————推荐
        await Promise.all(arr)
        // 顺序进行，且
        // await checkParity(n)
        // await check10(n)
      }
      let num = Number(this.num)
      console.time('t')
      check(num).then(() => {
        this.result = 'true'
        console.timeEnd('t')
      }).catch((e) => {
        this.result = 'false'
        console.error(e)
        console.timeEnd('t')
      })
      // console.timeEnd('t')
      function checkParity (n) { // 判断奇偶性
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            if (n % 2 === 0) {
              resolve()
            } else {
              reject(
                new Error(1)
              )
            }
          }, 1000)
        })
      }
      function check10 (n) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            if (n > 10) {
              resolve()
            } else {
              reject(
                new Error(2)
              )
            }
          }, 2000)
        })
      }
    }
  }
}
</script>
